package com.yun.simplequeue;

import com.rabbitmq.client.*;
import com.yun.utils.ConnectionUtil;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consume {

    @Test
    public void test() throws IOException, TimeoutException {
        //创建mq的连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置rabbitmq连接服务器
        factory.setHost("192.168.231.133");
        //设置端口
        factory.setPort(5672);
        //用户名
        factory.setUsername("guest");
        //密码
        factory.setPassword("guest");
        //设置需要连接的那台虚拟机
        factory.setVirtualHost("/");

        //创建连接
        Connection connection = factory.newConnection();

        //创建通道
        Channel channel = connection.createChannel();
        //绑定到队列
        channel.queueDeclare("hello",true,false,true,null);
        //消费消息
        //参数1：消费那个队列中的消息 队列名称
        //参数2：开启消息的自动确认机制
        //参数3：消费时的回调接口
        channel.basicConsume("hello",true,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("msg = "+ new String(body));
            }
        });
    }
}
